import React,{ Component } from 'react'
import { Form, Input, Button, Spin, Icon, message } from 'antd'
import { connect } from 'dva'
import 'antd/dist/antd.css';
import styles from "./styles.css";
//import md5 from 'js-md5';  const str=md5("HAPPY");

const FormItem = Form.Item;

class Register extends Component {

    constructor(props){
        super(props);
        this.state = {
            confirmDirty: false
        };
        this.form = this.props.form;
        this.dispatch = this.props.dispatch;
        this.formstyle = {
            width: "300px",
            height: "200px",
            position: "absolute",
            left: "50%",
            top: "40%",
            margin: "-100px 0 0 -150px "
          }
    }


    handleSubmit = (e) => {
        e.preventDefault();
        this.form.validateFields((err, values)=>{
            if(!err){
                const {confirmPwd,...data} = values;
                this.dispatch({
                    type: 'Login/register', data
                }).then(res =>{
                    if(res.RESULT){
                        message.success('注册成功');
                        this.props.onclick()
                    }else{
                        message.error(res.RESPONSE)
                    }
                })
            }
        })
    };

    handleBlur = (e, type) => {
        const value = e.target.value;
        switch (type){
            case 'username':
                this.props.form.validateFields(['username'], { force: true });
                break;
            case 'confirmPwd':
                this.setState({ confirmDirty: this.state.confirmDirty || !!value });
                break;
            default:
        }
    };

    /**
     * 校验回调接口：强制让ConfirmPwd进行校验
     * @param rule
     * @param value
     * @param callback
     */
    validateToConfirmPwd = (rule, value, callback) => {
        const form = this.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirmPwd'], { force: true });
        }
        callback();
    };

    /**
     * 校验回调接口：校验确认密码与密码是否一致
     * @param rule
     * @param value
     * @param callback
     */  
    compareToPassword = (rule, value, callback) => {
        const form = this.form;
        if (value && value !== form.getFieldValue('PassWord')) {
            callback('与密码不一致');
        } else {
            callback();
        }
    };
    render() {
        const { getFieldDecorator } = this.props.form;
        return (
            <div style={this.formstyle}>
                <Spin spinning={this.props.loading}>
                    <Form onSubmit={this.handleSubmit}>
                    <h2 style={{textAlign:"center"}}>注册页面</h2>
                        <FormItem hasFeedback >
                            {
                                getFieldDecorator('LoginName',
                                    {
                                        rules: [
                                            {
                                                validateTrigger:'onChange',
                                                required: true,
                                                message: '用户名不能为空',
                                            },{
                                                validateTrigger:'onChange',
                                                min: 4,
                                                max: 12,
                                                message: '长度必须控制在在4-12范围内',
                                            }
                                        ]
                                    }
                                )(
                                    <Input placeholder={'请输入用户名（必填）'}  prefix={<Icon type={'user'} />} onBlur={(e)=>this.handleBlur(e,'username')} />,
                                )
                            }
                        </FormItem>
                        <FormItem hasFeedback>
                            {
                                getFieldDecorator('PassWord',
                                    {
                                        validateFirst: true,
                                        rules: [
                                            {
                                                required: true,
                                                message: '密码不能为空',
                                            },{
                                                validator: this.validateToConfirmPwd,
                                            },{
                                                min: 6,
                                                max: 16,
                                                message: '密码长度必须控制在6-16范围内',
                                            }
                                        ]
                                    }
                                )(
                                    <Input type={'password'} prefix={<Icon type={'lock'} />} placeholder={'请输入密码（必填）'}/>,
                                )
                            }
                        </FormItem>
                        <FormItem hasFeedback>
                            {
                                getFieldDecorator('confirmPwd',
                                    {
                                        validateFirst: true,
                                        rules: [
                                            {
                                                required: true,
                                                message: '确认密码不能为空',
                                            },{
                                                validator: this.compareToPassword,
                                            },{
                                                min: 6,
                                                max: 16,
                                                message: '密码长度必须控制在6-16范围内',
                                            }
                                        ]
                                    }
                                )(
                                    <Input type={'password'} prefix={<Icon type={'lock'} />} placeholder={'请输入确认密码（必填）'} onBlur={(e)=>this.handleBlur(e,'confirmPwd')}/>,
                                )
                            }
                        </FormItem>			
                        <Button   className={styles.login_button} type={'primary'} htmlType={'submit'}>注册</Button>
                        <Button   className={styles.register_button} type={'primary'} onClick={this.props.onclick}>返回</Button>
                    </Form>
                </Spin>
            </div>
        );
    }
}

export default connect(
    ({loading})=>{
        return {
            loading: !!loading.models.Login
        }
    },null)(Form.create({})(Register))
